package com.ds.robot.assistant.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ds.robot.assistant.dao.TargetAchievementDao;
import com.ds.robot.assistant.entity.TargetAchievementEntity;
import com.ds.robot.assistant.enums.ChangeDirection;
import com.ds.robot.assistant.enums.PrincipalType;
import com.ds.robot.assistant.service.TargetAchievementService;
import com.ds.robot.assistant.service.TargetOkrService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;


@Service("targetAchievementService")
@Slf4j
public class TargetAchievementServiceImpl extends ServiceImpl<TargetAchievementDao, TargetAchievementEntity> implements TargetAchievementService {

    @Autowired
    private TargetOkrService targetOkrService;

    @Value("${app.quarter:2024H2}")
    private String quarter;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkAndProcessData() {
        int count = targetOkrService.queryOkrItemCount(quarter);
        LocalDate today = LocalDate.now();
        LocalDate thisSaturday = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.SATURDAY));
        log.info("本周六: {}", thisSaturday);

        // 1.查询achievementDate=昨天的所有数据
        List<TargetAchievementEntity> achievementList = this.lambdaQuery().eq(TargetAchievementEntity::getAchievementDate, thisSaturday).list();
        if (CollectionUtils.isEmpty(achievementList) || achievementList.size() < count) {
            throw new RuntimeException("当前数据量异常，请检查任务是否正常执行");
        }

        // 得到上周六的日期
        LocalDate lastWeek = thisSaturday.minusWeeks(1);

        //查询achievementDate=上周六的所有数据
        Date lastWeekDate = Date.from(lastWeek.atStartOfDay(ZoneId.systemDefault()).toInstant());
        // LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 传递LocalDate Date都行
        List<TargetAchievementEntity> lastAchievementList = this.lambdaQuery().eq(TargetAchievementEntity::getAchievementDate, lastWeek).list();
        log.debug("====lastAchievementList = {}", lastAchievementList);


        // 循环遍历achievementList，每条数据和上周六的数据进行比较，比较的依据是targetTypeId，principalType 和本数据相同

        for (TargetAchievementEntity entity : achievementList) {
            Integer targetTypeId = entity.getTargetTypeId();
            PrincipalType principalType = entity.getPrincipalType();

            Optional<TargetAchievementEntity> optional = lastAchievementList.stream().filter(achievement -> achievement.getTargetTypeId().equals(targetTypeId)
                    && achievement.getPrincipalType().equals(principalType)).findFirst();
            if (!optional.isPresent()) {
                // 抛出异常
                throw new RuntimeException(String.format("找不到对应的上周数据：%s,%s", targetTypeId, principalType.name()));
            }
            TargetAchievementEntity lastAchievement = optional.get();

            BigDecimal lastAchievementValue = lastAchievement.getValue();
            BigDecimal value = entity.getValue();

            //以lastAchievementValue作为基础，计算本周和上周相比，上升，下降的百分比，并更新到本周数据的changeValue中
            BigDecimal changeAbs;
            if (lastAchievementValue.compareTo(BigDecimal.ZERO) == 0) {
                changeAbs = BigDecimal.ONE;
            } else {
                changeAbs = lastAchievementValue.subtract(value).divide(lastAchievementValue, 4, RoundingMode.HALF_UP).abs();
            }
            entity.setChangeValue(changeAbs);
            if (lastAchievementValue.compareTo(value) > 0) {
                entity.setChangeDirection(ChangeDirection.D);
            } else if (lastAchievementValue.compareTo(value) < 0) {
                entity.setChangeDirection(ChangeDirection.U);
            } else {
                entity.setChangeDirection(ChangeDirection.S);
            }
        }
        achievementList.forEach(System.out::println);

        for (TargetAchievementEntity entity : achievementList) {
            entity.setTargetTypeId(null);
            entity.setAchievementDate(null);
            entity.setValue(null);
            entity.setValueType(null);
            entity.setPrincipalType(null);
            entity.setRemark(null);
            entity.setCreatedAt(null);
            entity.setUpdatedAt(null);
        }
        // 批量更新数据
        this.updateBatchById(achievementList);


        // Map<Integer, Map<PrincipalType, List<TargetAchievementEntity>>> mapMap = achievementList.stream()
        //         .collect(Collectors.groupingBy(TargetAchievementEntity::getTargetTypeId,
        //                 Collectors.groupingBy(TargetAchievementEntity::getPrincipalType)));
        //
        // for (Map.Entry<Integer, Map<PrincipalType, List<TargetAchievementEntity>>> mapEntry : mapMap.entrySet()) {
        //     Integer typeId = mapEntry.getKey();
        //     Map<PrincipalType, List<TargetAchievementEntity>> valueMap = mapEntry.getValue();
        //     for (Map.Entry<PrincipalType, List<TargetAchievementEntity>> entry : valueMap.entrySet()) {
        //         PrincipalType principalType = entry.getKey();
        //         List<TargetAchievementEntity> list = entry.getValue();
        //         BigDecimal value = Optional.ofNullable(list).map(l -> l.get(0)).map(TargetAchievementEntity::getValue).orElse(BigDecimal.ZERO);
        //
        //     }
        // }
        //
        // Map<Integer, Map<PrincipalType, List<TargetAchievementEntity>>> lastWeekMap = lastAchievementList.stream().collect(Collectors.groupingBy(TargetAchievementEntity::getTargetTypeId,
        //         Collectors.groupingBy(TargetAchievementEntity::getPrincipalType)));
    }

    private static Date getToday1() {
        Calendar calendar = Calendar.getInstance();
        // 设置时间（00:00:00）
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        return calendar.getTime();
    }

    private static Date getToday3() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = sdf.format(new Date());
        try {
            return sdf.parse(dateString);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        // 获取今天的日期
        LocalDate today = LocalDate.now();
        // 获取本周六的日期
        LocalDate thisSaturday = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.SATURDAY));
        System.out.println("本周六的日期: " + thisSaturday);

        // 获取上周六的日期
        LocalDate lastSaturday = thisSaturday.minusWeeks(1);
        System.out.println("上周六的日期: " + lastSaturday);

        // Date today1 = getToday1();
        // System.out.println("today1 = " + today1);
        // Date today2 = DateUtil.getYesterday();
        // System.out.println("today2 = " + today2);
        // Date today3 = getToday3();
        // System.out.println("today3 = " + today3);
    }
}
